package com.jjwxc.jwjskandriod.widget;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.WebActivity;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFApplication;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.model.PayResult;
import com.jjwxc.jwjskandriod.model.RechargePriceResponse;
import com.jjwxc.jwjskandriod.model.RechargeResponse;
import com.jjwxc.jwjskandriod.model.UserBalanceResponse;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class BuyWjbPop {
    Activity context;
    TextView tv_balance_yue;
    PopupWindow popWindow;

    @SuppressLint("ClickableViewAccessibility")
    public void buyWjbWindow(View v, Activity context, String chapterPrice, BuyWjbListener wjbListener) {
        this.context = context;
        View view = LayoutInflater.from(context).inflate(R.layout.buy_wjb_pop, null, false);

        List<LinearLayout> llList = new ArrayList<>();
        List<TextView> wjbList = new ArrayList<>();
        List<TextView> priceList = new ArrayList<>();

        View vdis = view.findViewById(R.id.view);
        tv_balance_yue = view.findViewById(R.id.tv_balance_yue);
        LinearLayout ll_gmxy = view.findViewById(R.id.ll_gmxy);
        TextView tv_chapter_rice = view.findViewById(R.id.tv_chapter_rice);

        LinearLayout ll_coin_one = view.findViewById(R.id.ll_coin_one);
        TextView tv_wjb_one = view.findViewById(R.id.tv_wjb_one);
        TextView tv_price_one = view.findViewById(R.id.tv_price_one);
        llList.add(ll_coin_one);
        wjbList.add(tv_wjb_one);
        priceList.add(tv_price_one);

        LinearLayout ll_coin_two = view.findViewById(R.id.ll_coin_two);
        TextView tv_wjb_two = view.findViewById(R.id.tv_wjb_two);
        TextView tv_price_two = view.findViewById(R.id.tv_price_two);
        llList.add(ll_coin_two);
        wjbList.add(tv_wjb_two);
        priceList.add(tv_price_two);

        LinearLayout ll_coin_three = view.findViewById(R.id.ll_coin_three);
        TextView tv_wjb_three = view.findViewById(R.id.tv_wjb_three);
        TextView tv_price_three = view.findViewById(R.id.tv_price_three);
        llList.add(ll_coin_three);
        wjbList.add(tv_wjb_three);
        priceList.add(tv_price_three);

        tv_chapter_rice.setText("实付 余额" + chapterPrice + "完结币  余额不足请充值");
        int height = context.getResources().getDisplayMetrics().heightPixels;// 屏幕的高
        //1.构造一个PopupWindow，参数依次是加载的 View，宽高
        popWindow = new PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT
                , height + getStatusBarHeight(context), true);
        popWindow.setAnimationStyle(R.anim.anim_pop);  //设置加载动画

        //这些为了点击非PopupWindow区域，PopupWindow会消失的，如果没有下面的
        //代码的话，你会发现，当你把PopupWindow显示出来了，无论你按多少次后退键
        //PopupWindow并不会关闭，而且退不出程序，加上下述代码可以解决这个问题

        popWindow.setTouchable(true);
        popWindow.setTouchInterceptor((v1, event) -> false);
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                wjbListener.onItemClick(true);
            }
        });
        vdis.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popWindow.dismiss();
            }
        });
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));    //要为popWindow设置一个背景才有效

        //设置 popupWindow 显示的位置，参数依次是参照 View，x轴的偏移量，y轴的偏移量
        popWindow.showAsDropDown(v, 20, 0);
        //获取余额
        getBalance(tv_balance_yue);

        ll_gmxy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(context, WebActivity.class);
                intent.putExtra("WEB_URL", Url.help4);
                intent.putExtra("WEB_NAME", "购买须知");
                context.startActivity(intent);
            }
        });

        //获取购买列表
        new FFNetWork().post(Url.getRechargePrice, "", new FFNetWorkCallBack<RechargePriceResponse>() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(RechargePriceResponse response) {
                if (response.getCode() == 200 && response.getData().size() == 3) {
                    List<RechargePriceResponse.DataBean> beanList = response.getData();
                    for (int i = 0; i < llList.size(); i++) {
                        priceList.get(i).setText("￥" + StUtils.percentage(beanList.get(i).getPaymentAmount()));
                        wjbList.get(i).setText(beanList.get(i).getAmount() + "完结币");
                        if (i == 0) {
                            llList.get(i).setBackgroundResource(R.drawable.recharge_select_true);
                            priceList.get(i).setTextColor(Color.parseColor("#4D998D"));
                            wjbList.get(i).setTextColor(Color.parseColor("#4D998D"));
                        } else {
                            llList.get(i).setBackgroundResource(R.drawable.recharge_select_false);
                            priceList.get(i).setTextColor(Color.parseColor("#000000"));
                            wjbList.get(i).setTextColor(Color.parseColor("#000000"));
                        }
                        int finalI = i;
                        llList.get(i).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                for (int s = 0; s < llList.size(); s++) {
                                    if (finalI == s) {
                                        llList.get(s).setBackgroundResource(R.drawable.recharge_select_true);
                                        priceList.get(s).setTextColor(Color.parseColor("#4D998D"));
                                        wjbList.get(s).setTextColor(Color.parseColor("#4D998D"));
                                        //开始购买
                                        recharge(beanList.get(s).getProductId());
                                        if (s == 0) {
                                            MobclickAgent.onEvent(context, UMConstant.Event_Recharge_ + "30");
                                        } else if (s == 1) {
                                            MobclickAgent.onEvent(context, UMConstant.Event_Recharge_ + "100");
                                        } else if (s == 2) {
                                            MobclickAgent.onEvent(context, UMConstant.Event_Recharge_ + "200");
                                        }
                                    } else {
                                        llList.get(s).setBackgroundResource(R.drawable.recharge_select_false);
                                        priceList.get(s).setTextColor(Color.parseColor("#000000"));
                                        wjbList.get(s).setTextColor(Color.parseColor("#000000"));
                                    }
                                }
                            }
                        });
                    }

                }

            }

            @Override
            public boolean onFail(RechargePriceResponse response) {
                return false;
            }
        }, RechargePriceResponse.class, "{\"device\":\"android\"}");

    }

    public void recharge(String selectId) {
        new FFNetWork().post(Url.recharge, null, new FFNetWorkCallBack<RechargeResponse>() {
            @Override
            public void onSuccess(RechargeResponse response) {
                if (response.getCode() == 200) {
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(context);
                            Map<String, String> result = alipay.payV2(response.getData().getOrderStr(), true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();

                }

            }

            @Override
            public boolean onFail(RechargeResponse response) {
                return false;
            }
        }, RechargeResponse.class, "{\"device\":\"android\",\"productId\":  \"" + selectId + "\"}");
    }

    final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == SDK_PAY_FLAG) {
                PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                /**
                 * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                 */
                String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为9000则代表支付成功
                if (TextUtils.equals(resultStatus, "9000")) {
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
//                    buySubscribe(mBookId, chapterId,  tv_balance_yue);
                    FFApplication.showToast("支付完成");
                } else {
                    // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                    Log.e("充值失败-", payResult.toString());
                    FFApplication.showToast("支付完成");
                }
            }
        }
    };

    //购买章节并刷新
//    public void buySubscribe(String mBookId, String chapterId, TextView tv_balance_yue) {
//        SubscribeRequest request = new SubscribeRequest();
//        request.setBookId(mBookId);
//        request.setSubscribeType("single");
//        List<String> ids = new ArrayList<>();
//        ids.add(chapterId);
//        request.setChapterIds(ids);
//        new FFNetWork().post(Url.subscribe, null, new FFNetWorkCallBack<String>() {
//            @SuppressLint("CheckResult")
//            @Override
//            public void onSuccess(String response) {
//                if (response.contains("200")) {
//                    //删除未购买已经缓存的空章节
//                    FileUtils.chapterCachedDelete(mBookId, chapterId);
//                    //更新余额
//                    getBalance(tv_balance_yue);
//                    //购买成功刷新
//                    //目录和章节
//                    // 刷新章节列表
//                    ((ReadActivity) context).refreshBookCategory(true);
//                    popWindow.dismiss();
//                }
//            }
//
//            @Override
//            public boolean onFail(String response) {
//                return false;
//            }
//        }, String.class, JSON.toJSONString(request));
//    }

    public void getBalance(TextView tv_balance_yue) {
        new FFNetWork().post(Url.balance, null, new FFNetWorkCallBack<UserBalanceResponse>() {
            @Override
            public void onSuccess(UserBalanceResponse response) {
                if (response.getCode() == 200) {
                    tv_balance_yue.setText("余额" + response.getData().getBalance() + "完结币");
                }

            }

            @Override
            public boolean onFail(UserBalanceResponse response) {
                return false;
            }
        }, UserBalanceResponse.class);
    }

    /**
     * 获取状态栏高度
     *
     * @param context context
     * @return 状态栏高度
     */
    public int getStatusBarHeight(Context context) {
        // 获得状态栏高度
        @SuppressLint("InternalInsetResource")
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        return context.getResources().getDimensionPixelSize(resourceId);
    }

    public interface BuyWjbListener {
        void onItemClick(boolean value);
    }
}
